package com.hundsun.yr.universal.p2p.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.Utils.HeaderMap;
import com.hundsun.yr.universal.library.base.BaseAppManager;
import com.hundsun.yr.universal.library.base.BaseWebActivity;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils.NetType;
import com.hundsun.yr.universal.library.utils.RegularUtils;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSEditText;
import com.hundsun.yr.universal.p2p.bean.BankAccountBeen;
import com.hundsun.yr.universal.p2p.bean.BankEntity;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializePresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.InitializeView;
import com.hundsun.yr.universal.p2p.widget.ValidateButton;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;


/**
 * @version V1.0
 * @Title: BindCardZWGTActivity.java
 * @Description: 认证-开户|绑卡
 * @date 2016-3-3 下午12:35:33
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class BindCardActivity extends BaseActivity implements InitializeView, OnClickListener {
    /** 手机号输入框 **/
//	private HSEditText et_moble = null;
    /**
     * 银行卡号输入框
     **/
    private HSEditText et_bankcard = null;
    /**
     * 银行
     **/
//    private ItemView item_bankcard = null;
    /**
     * 选中银行信息
     **/
    private BankEntity bank = null;
    /**
     * 开户按钮
     **/
    private HSButton btn_openaccount = null;
    /** 更改手机号按钮 **/
//	private HSButton btn_modifyLoginMobile = null;
    /**
     * 请求接口
     **/
    private static RequestPresenter mPresenter = null;
    /**
     * 银行卡号
     **/
    private String cardNo;
    /**
     * 身份证号
     **/
    private String certNo;
    /**
     * 手机号
     **/
    private String mobile = "";
    /**
     * 用户姓名
     **/
    private String userName;
    /**
     * 银行号
     **/
    private String bankNo;
    /**
     * 银行名称
     **/
    private String bankName;
    /**
     * 协议选择
     **/
//    private CheckBox ck_agree = null;
    /**
     * 银行帐户存管三方协议
     **/
    private TextView tv_protocol_1 = null;
    /**
     * 用户授权协议
     **/
    private TextView tv_protocol_2 = null;
    /**快捷充值提示**/
//    private TextView tv_quicktips=null;
    /**
     * 预留手机号
     **/
    private TextView tv_mobile = null;

    /**
     * 支持银行卡
     */
    private TextView tv_support_bank = null;

    /**
     * 验证码
     */
    private HSEditText et_vcode = null;

    /**
     * 验证码按钮
     */
    private ValidateButton btn_vcode = null;
    private String zwgt_data;

    /**
     * 绑卡人姓名
     */
    private TextView tv_bind_card_name = null;

    /**
     * 开户人身份证
     */
    private TextView tv_bind_card_certno = null;


    private String vCode;
    private BankAccountBeen bankAccountBeen;

//    private ImageView iv_bind_card_scan = null;

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return true;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {

        certNo = extras.getString(UserInfo.CERT_NO);
        userName = extras.getString(UserInfo.REALNAME);
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_open_account;
    }

    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {

    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    protected void initViewsAndEvents() {
        //是否开户
        setToolbarTitle(R.string.binding_card);
        btn_openaccount = findView(R.id.btn_openaccount);
        tv_support_bank = findView(R.id.tv_support_bank);

        tv_bind_card_name = findView(R.id.tv_bind_card_name);
        tv_bind_card_certno = findView(R.id.tv_bind_card_certno);

//        iv_bind_card_scan = findView(R.id.iv_bind_card_scan);

        /**
         * 预留姓名
         */
        if (sharedPreferences.getShareProf(UserInfo.REAL_USER_NAME) != null && !sharedPreferences.getShareProf(UserInfo.REAL_USER_NAME).isEmpty()) {
            tv_bind_card_name.setText(CommTool.encodName(sharedPreferences.getShareProf(UserInfo.REAL_USER_NAME)));
        }

        /**
         * 展示加密身份证号
         */
        if (sharedPreferences.getShareProf(UserInfo.CERT_NO) != null && !sharedPreferences.getShareProf(UserInfo.CERT_NO).isEmpty()) {
            tv_bind_card_certno.setText(CommTool.encodCertNo(sharedPreferences.getShareProf(UserInfo.CERT_NO)));
        }

        /**
         * 预留手机号
         */
        tv_mobile = findView(R.id.tv_mobile);
        tv_mobile.setText("");
        mobile = sharedPreferences.getShareProf(UserInfo.BANKMOBILE);
        if (mobile != null && !mobile.isEmpty()) {
            tv_mobile.setText(CommTool.encodPhone(mobile));
        }

        et_bankcard = findView(R.id.et_bankcard);

        //初始化验证码按钮
        et_vcode = findView(R.id.et_vcode);
        btn_vcode = findView(R.id.btn_vcode);
        tv_support_bank.setOnClickListener(this);
        btn_openaccount.setOnClickListener(this);
        btn_vcode.setOnClickListener(this);
//        iv_bind_card_scan.setOnClickListener(this);
        mPresenter = new InitializePresenterImpl(mContext, this);

    }

    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }

    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void onNetworkConnected(NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return true;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    public void onClick(View v) {
//        Bundle bundle = null;
        switch (v.getId()) {
            case R.id.btn_openaccount:
                // 请求
                //request();
                break;

            case R.id.btn_vcode:
                sendVcode(mobile);
                break;

            case R.id.tv_support_bank:
                //支持的银行卡
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                HashMap mHeader2 = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.h5_index) + TaskConstants.TASK_BANKCARDLIST,
                        "", mConfigSP.getShareProf(TaskConstants.TASK_CONFIG), zwgt_data);
                HeaderMap headerMap2 = new HeaderMap();
                headerMap2.setMap(mHeader2);

                Bundle bundle2 = new Bundle();
                bundle2.putString(BaseWebActivity.BUNDLE_KEY_URL, mContext.getString(R.string.root_h5_url_test) + getString(R.string.h5_index) + TaskConstants.TASK_BANKCARDLIST);
                bundle2.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap2);
                bundle2.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.bankcard));
                bundle2.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.HTTP.getIntValue());
                bundle2.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGo(WebActivity.class, bundle2);


                break;
//            case R.id.iv_bind_card_scan:
//                readyGoForResult(ScanCamera.class,456);
//                break;
        }
    }

    /**
     * 请求校验
     */
    private void request() {
        cardNo = et_bankcard.getBank();
//        mobile = tv_mobile.getPhone().toString();
        vCode = et_vcode.getText().toString();

        /**检查银行卡**/
        if (TextUtils.isEmpty(cardNo)) {
            showToast(R.string.input_bind_card);
            return;
        } else if (cardNo.length() < 14) {
            showToast(getString(R.string.can_user_bankno));
            return;
        }

        if (!RegularUtils.isPhoneNum(mobile)) {
            showToast(R.string.input_format_mobile);
            return;
        }

        if (TextUtils.isEmpty(vCode)){
            showToast(getString(R.string.input_mobile_code));
            return;
        }

        if (vCode.length() != 6){
            showToast(getString(R.string.error_vcode));
            return;
        }

        //绑定银行卡
        String zwgt_data = BaseRequestTool2.getFormatedDateString();
        JSONObject map = new JSONObject();
        try {
//            Logs.e("mobile: " + mobile + ",cardno: " + cardNo + ",code:" + vCode);
            map.put("mobile", mobile);
            map.put("cardno", cardNo);
            map.put("code", vCode);
            sharedPreferences.getShareProf(UserInfo.USER_NO);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);

        mPresenter.loadingData(TaskConstants.TASK_CARDBIND, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.TASK_CARDBIND, Constants.EVENT_DATA,
                jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, getString(R.string.api_user_test) + TaskConstants.TASK_CARDBIND, sharedPreferences.getShareProf(UserInfo.USER_NO),
                        sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
    }

    @Override
    protected void onDestroy() {
//		stopAlarmIntent();
        super.onDestroy();
    }


    @Override
    public <T> void initializeViews(String task_name, T data) {
        // TODO Auto-generated method stub
        switch (task_name) {
            case TaskConstants.TASK_CARDBIND:
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                mPresenter.loadingData(TaskConstants.TASK_BANK_ACCOUNT, getString(R.string.root_url_test) + getString(R.string.api_user_test) +
                        TaskConstants.TASK_BANK_ACCOUNT, Constants.EVENT_BEGIN, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test)
                        + TaskConstants.TASK_BANK_ACCOUNT, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
                break;

            case TaskConstants.TASK_BANK_ACCOUNT:
                //查询托管账户信息，更新ui
                bankAccountBeen = (BankAccountBeen) data;
                //保存余额信息
//                sharedPreferences.putShareProf(UserInfo.CAN_USE_MONEY, bankAccountBeen.availBal);

                //对江西银行卡信息进行显示
                if (!bankAccountBeen.depository_bank_no.isEmpty()) {//如果返回有银行卡信息，则将银行卡信息保存并且显示银行卡
                    //将获得的银行卡信息保存
                    sharedPreferences.putShareProf(UserInfo.JX_ACCOUNT_NO, bankAccountBeen.depository_bank_no);
                }

                //如果获取了用户的银行卡信息就将其绑定
                /**存储开户信息**/
                if (bankAccountBeen.depository_bank_no != null && !bankAccountBeen.depository_bank_no.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.JIANGXI_BANKCARD, bankAccountBeen.depository_bank_no);
                    sharedPreferences.putShareProf(UserInfo.IF_ACCOUNT, "YES");
                } else {
                    sharedPreferences.putShareProf(UserInfo.IF_ACCOUNT, "NO");
                }

                /**存储绑卡信息**/
                if (bankAccountBeen.bankCard != null && !bankAccountBeen.bankCard.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.BANKCARD, bankAccountBeen.bankCard);
                    sharedPreferences.putShareProf(UserInfo.BANKCARDNAME, bankAccountBeen.bankName);

                    sharedPreferences.putShareProf(UserInfo.IF_BINDCARD, "YES");
                } else {
                    sharedPreferences.putShareProf(UserInfo.IF_BINDCARD, "NO");
                }

                if (bankAccountBeen.true_name != null && !bankAccountBeen.true_name.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.REAL_USER_NAME, bankAccountBeen.true_name);
                }

                /**
                 * 绑定身份证
                 */
                if (bankAccountBeen.cert_no != null && !bankAccountBeen.cert_no.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.CERT_NO, bankAccountBeen.cert_no);
                }

                /**保存登陆手机号**/
                //保存手机号码
                if (bankAccountBeen.phone != null && !bankAccountBeen.phone.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.MOBILE, bankAccountBeen.phone);
                }

                /**
                 * 保存用户银行卡手机号
                 */
                if (bankAccountBeen.depository_bank_mobile != null && !bankAccountBeen.depository_bank_mobile.isEmpty()){
                    sharedPreferences.putShareProf(UserInfo.BANKMOBILE,bankAccountBeen.depository_bank_mobile);
                } else {
                    sharedPreferences.putShareProf(UserInfo.BANKMOBILE,"");
                }

/*            *//**保存用户交易密码设置状态**/
                if (bankAccountBeen.set_paypwd_flag != null && !bankAccountBeen.set_paypwd_flag.isEmpty()) {
                    if (TextUtils.equals(bankAccountBeen.set_paypwd_flag, "1")) {
                        //已经设置交易密码
                        sharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "YES");
                    } else {
                        sharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "NO");
                    }
                } else {
                    sharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "NO");
                }

                /**保存可用余额**/
                if (bankAccountBeen.availBal != null && !bankAccountBeen.availBal.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.CAN_USE_MONEY, bankAccountBeen.availBal);
                }

                //保存用户vip等级
                if (bankAccountBeen.vip != null && !bankAccountBeen.vip.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.VIPLEVEL, bankAccountBeen.vip);
                }

                showToast(getString(R.string.bindcard_success));

                if (BaseAppManager.getInstance().getActivity(MineBankCardActivity.class) != null){
                    BaseAppManager.getInstance().getActivity(MineBankCardActivity.class).finish();
                }

                finish();
                break;
        }
    }

    @Override
    public <T> void initializeError(String task_name, T data) {
        // TODO Auto-generated method stub
        if (TextUtils.isEmpty((String) data)) return;
    }

    /**
     * @version V1.0
     * @Title: AlarmReceiver.java
     * @Description: 定时广播
     * @date 2016-3-21 下午7:25:28
     * @author:hejun.shen
     * @email:shenhj15971@hundsun.com
     * @replace author:
     * @replace date:
     */
    public static class AlarmReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

        }

    }

    /**
     * 点击发送验证码
     */
    private void sendVcode(String phone) {
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        JSONObject map = new JSONObject();

        //检查是否输入手机号
        if (TextUtils.isEmpty(phone)) {
            showToast(R.string.input_bind_mobile);
            return;
        }

        //检查手机号格式
        if (!RegularUtils.isPhoneNum(phone)) {
            showToast(R.string.input_format_mobile);
            return;
        }

        try {
            map.put("srvtxcode", "cardBindPlus");
            map.put("phone", phone);
//            map.put("channel","0");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
        mPresenter.loadingData(TaskConstants.TASK_SMS_APPLY, mContext.getString(R.string.root_url_test) + mContext.getString(R.string.api_pub_test) + TaskConstants.TASK_SMS_APPLY, Constants.EVENT_DATA,
                jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, mContext.getString(R.string.api_pub_test) + TaskConstants.TASK_SMS_APPLY, sharedPreferences
                        .getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 456:
                if(data == null){
                    return;
                }

                char[] StringR = data.getCharArrayExtra("StringR");
                et_bankcard.setText(String.valueOf(StringR).trim());

                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("BindCardActivity");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("BindCardActivity");
        MobclickAgent.onPause(this);
    }
}
